/*
 * Copyright 2013 JROSE
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.jrose.core.jdbc.persistence.support;

import lombok.AccessLevel;
import lombok.Getter;
import lombok.NoArgsConstructor;
import org.jrose.core.jdbc.entity.EntityDefinition;
import org.jrose.core.jdbc.entity.EntityDefinitionFactory;
import org.jrose.core.jdbc.persistence.query.Query;
import org.springframework.util.Assert;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

/**
 * For providing entity definitions.
 *
 * @author Xiaohai Zhang
 * @since 2013-08-17 21:21
 */
@NoArgsConstructor(access = AccessLevel.PROTECTED)
abstract public class EntityDefinitionProvider<E extends Serializable> extends DatabaseConnectionProvider {
    @Getter protected EntityDefinition<E> entityDefinition;

    @Override
    public void afterPropertiesSet() throws Exception {
        super.afterPropertiesSet();

        Type genericSuperClass = getClass().getGenericSuperclass();
        //noinspection unchecked
        Class<E> entityClass = (Class<E>) ((ParameterizedType) genericSuperClass).getActualTypeArguments()[0];

        entityDefinition = EntityDefinitionFactory.getEntityDefinition(entityClass);
    }

    final protected void validatePrimaryKey(Serializable... ids) {
        if (!entityDefinition.hasPrimaryKey()) {
            throw new UnsupportedOperationException();
        }
        Assert.notNull(ids);
        Assert.isTrue(ids.length == entityDefinition.getPrimaryKeyFields().size());
    }

    final protected Query<E> createQuery() {
        return new Query<E>();
    }
}
